import React, { useState, useEffect } from "react";
import { Input, Button } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import "./index.scss";

interface IOption {
    label: string;
    value: string;
}
interface IOptionSettingProps {
    onChange: (options: IOption[]) => void;
    options?: IOption[];
}
const OptionSetting: React.FC<IOptionSettingProps> = (props) => {
    const [options, setOptions] = useState<IOption[]>(props.options || []);
    const addOption = () => {
        setOptions([...options, {label: "", value: ""}])
    }
    const setOptionLabel = (index: number, value: any) => {
        options[index].label = value;
        setOptions([...options])
    }
    const setOptionValue = (index: number, value: any) => {
        options[index].value = value;
        setOptions([...options])
    }
    useEffect(() => {
        props.onChange(options)
    }, [options, props])
    return <div className="option-setting-wrapper">
        {
            options.map((item, index) => {
                return (<div className="option-setting-item">
                <Input placeholder={"选项label值"} value={item.label} className="label-input" onChange={(e) => setOptionLabel(index, e.target.value)}></Input>
                <Input placeholder={"选项value值"} value={item.value} className="value-input" onChange={(e) => setOptionValue(index, e.target.value)}></Input>
                <Button danger type="primary" className="delete-btm" onClick={() => {options.splice(index, 1); setOptions([...options])}}><DeleteOutlined /></Button>
            </div>)
            })
        }
        <div className="add-btn">
            <Button onClick={() => addOption()}>添加选项</Button>
        </div>
    </div>
}

export default OptionSetting;